package com.javaforever.clocksimplejee4.facade;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baidu.ai.aip.utils.Base64Util;
import com.javaforever.clocksimplejee4.domain.ClockRecord;
import com.javaforever.clocksimplejee4.domain.User;
import com.javaforever.clocksimplejee4.service.ClockRecordService;
import com.javaforever.clocksimplejee4.service.PrivilegeService;
import com.javaforever.clocksimplejee4.service.UserService;
import com.javaforever.clocksimplejee4.serviceimpl.ClockRecordServiceImpl;
import com.javaforever.clocksimplejee4.serviceimpl.FaceServiceImpl;
import com.javaforever.clocksimplejee4.serviceimpl.PrivilegeServiceImpl;
import com.javaforever.clocksimplejee4.serviceimpl.UserServiceImpl;
import com.javaforever.clocksimplejee4.utils.AppTokenManager;
import com.javaforever.clocksimplejee4.utils.StringUtil;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class ClockRecordClockController
 */
public class FaceLoginFacade extends HttpServlet {
     protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	     response.setContentType("text/html;charset=UTF-8");
	     PrintWriter out = response.getWriter();
	     Map<String, Object> result = new TreeMap<String,Object>();
	     try {
	    	 String imageData = request.getParameter("image");
	         String description = request.getParameter("description");
	         if (StringUtil.isBlank(description)) description = "";
	         
	    	 UserService userService = new UserServiceImpl();	    	 
	         User user = userService.findUserByFace(imageData);
        	 user.setPassword("");
        	 user.setConfirmpassword("");
        	 user.setPin("");
        	 user.setImageData1("");
        	 FaceServiceImpl fimpl = new FaceServiceImpl();
        	 if (user.getId()>0 && user.getScore() > 78d && fimpl.detectOneValidFace(Base64Util.decode(imageData))) {
		         boolean isAdmin = "Y".equalsIgnoreCase(user.getIsadmin()!=null?user.getIsadmin():"")?true:false;
		         String forwardUrl = "../jsp/cameraclockhome.jsp";
		         ClockRecordService clockRecordService = new ClockRecordServiceImpl();
		         long cid = clockRecordService.clock(user, description);
		         ClockRecord cr = clockRecordService.findClockRecordById(cid);
		         
		         PrivilegeService privService = new PrivilegeServiceImpl();
		         boolean canAccess = privService.canAccess(user, forwardUrl);
			     Set<String> canAccessUrls = privService.listMyPrivilegeUrls(isAdmin);
			     String token = AppTokenManager.addUserId(user.getId(),canAccessUrls);
			     
			     request.getSession().setAttribute("canAccess", canAccess==true?"Y":"N");
			    	if (isAdmin &&canAccess){
			    		request.getSession(true).setAttribute("userData", user);
			        	request.getSession(true).setAttribute("islogin", "Y");
			        	request.getSession(true).setAttribute("empid", user.getEmpid());
			        	request.getSession(true).setAttribute("isadmin", user.getIsadmin());
			        	
			    		result.put("forwardUrl",forwardUrl);
			    		result.put("success", true);
			    		result.put("token", token);
			    		result.put("user", user);
			    		result.put("clockRecord", cr);
			    		System.out.println("JerryDeubug:facelogin:"+JSONObject.fromObject(result));
			        	out.println(JSONObject.fromObject(result));
			        	return;
			    	} else if (!isAdmin){
			        	request.getSession(true).setAttribute("userData", user);
			        	request.getSession(true).setAttribute("islogin", "Y");
			        	request.getSession(true).setAttribute("empid", user.getEmpid());
			        	 request.getSession(true).setAttribute("isadmin", user.getIsadmin());
			        	
			    		result.put("forwardUrl",forwardUrl);
			    		result.put("success", true);
			    		result.put("token", token);
			    		result.put("user", user);
			    		result.put("clockRecord", cr);
			    		System.out.println("JerryDeubug:facelogin:"+JSONObject.fromObject(result));
			        	out.println(JSONObject.fromObject(result));
			        	return;
			    	}
		    	} else {
		        	request.getSession(true).setAttribute("userData","");
		        	request.getSession(true).setAttribute("islogin", "");
		        	request.getSession(true).setAttribute("empid", "");
		        	request.getSession(true).setAttribute("isadmin","");
		    		result.put("forwardUrl","../login/index.html");
		    		result.put("success", false);
		    		result.put("clockRecord", null);
		    		result.put("scroe", user.getScore());
		        	out.println(JSONObject.fromObject(result));
		        	return;
		    	}
	     } catch (Exception e){
	    	 e.printStackTrace();
	    	 result.put("success", false);
             result.put("errorMessage", e.getMessage());
             result.put("forwardUrl", "../login/cameralogin.html");
             out.println(JSONObject.fromObject(result));
          } finally {
	         out.close();
	     }
 }


 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
 /**
  * Handles the HTTP <code>GET</code> method.
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
     processRequest(request, response);
 }

 /**
  * Handles the HTTP <code>POST</code> method.
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
     processRequest(request, response);
 }

 /**
  * Returns a short description of the servlet.
  * @return a String containing servlet description
  */
 @Override
 public String getServletInfo() {
     return "Short description";
 }// </editor-fold>

}
